use std::sync::Arc;
use actix_web::web::{Json, Path};
use actix_web::{get, post, web::Data, Responder};
use sqlx::MySqlPool;
use crate::business::entity::user::User;
use crate::business::service::user_service::UserService;
use crate::extends::core::context::app_context_beans::AppContextBeans;
use crate::extends::core::errors::response_code_enums::ResponseCodeEnum;
use crate::extends::core::http::request_headers::RequestHeaders;
use crate::extends::core::pager::page_helper::PageHelper;
use crate::extends::core::response::reponse_data::*;

/// 处理用户分页查询请求
///
/// # 参数
/// * `vo` - 包含分页信息的JSON对象
/// * `pool` - MySQL数据库连接池
///
/// # 返回值
/// 返回包含用户列表的JSON响应
#[post("/admin/user/list")]
pub async fn list(
    headers: RequestHeaders,
    Json(search): Json<PageHelper<User>>,
    ctx_beans: Data<AppContextBeans>
) -> impl Responder {
    log::info!("{:?} ", search);
    headers.print();
    let user_service: Arc<UserService> = match ctx_beans.get_bean("user_service") {
        Ok(service) => service,
        Err(err) => {
            log::error!("Failed to retrieve user_service: {}", err);
            return R::error(ResponseCodeEnum::INTERNAL_SERVER_ERROR); // 返回合适的错误响应
        }
    };
    let result = user_service.find(&search).await;
    return R::success(Some(result));
}

/// 处理保存新用户的请求
///
/// # 参数
/// * `vo` - 包含用户详细信息的JSON对象
/// * `pool` - MySQL数据库连接池
///
/// # 返回值
/// 返回指示操作成功或失败的JSON响应
#[post("/admin/user/save")]
pub async fn save(Json(vo): Json<User>, pool: Data<MySqlPool>) -> impl Responder {
    log::info!("{:?} ", vo);
    let result = User::save(&vo, &pool).await;
    return R::success(result);
}

/// 处理根据ID删除用户的请求
///
/// # 参数
/// * `id` - 要删除的用户ID
/// * `pool` - MySQL数据库连接池
///
/// # 返回值
/// 返回指示操作成功或失败的JSON响应
#[get("/admin/user/delete/{id}")]
pub async fn delete(id: Path<i32>, pool: Data<MySqlPool>) -> impl Responder {
    log::info!("{:?} ", id);
    let result = User::delete(&id, &pool).await;
    return R::success(result);
}

/// 处理更新用户详细信息的请求
///
/// # 参数
/// * `vo` - 包含更新后用户详细信息的JSON对象
/// * `pool` - MySQL数据库连接池
///
/// # 返回值
/// 返回指示操作成功或失败的JSON响应
#[post("/admin/user/update")]
pub async fn update(Json(vo): Json<User>, pool: Data<MySqlPool>) -> impl Responder {
    log::info!("{:?} ", vo);
    let result = User::update(&vo, &pool).await;
    return R::success(result);
}

/// 处理根据ID获取用户详细信息的请求
///
/// # 参数
/// * `id` - 要检索的用户ID
/// * `pool` - MySQL数据库连接池
///
/// # 返回值
/// 返回包含用户详细信息的JSON响应
#[get("/admin/user/detail/{id}")]
pub async fn detail(id: Path<i32>, pool: Data<MySqlPool>) -> impl Responder {
    log::info!("{:?} ", id);
    let result = User::find_by_id(&id, &pool).await;
    return R::success(result);
}
